// 1. React核心库
import React, { useEffect } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, Form, Input, Select, Switch, Space, message } from 'antd';

// 4. 专业组件库
import { ProForm, ProFormText, ProFormSelect, ProFormSwitch, ProFormTextArea } from '@ant-design/pro-components';

// 5. 工具库
 
// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { AIProvider } from '@/services/generated';

interface ProviderFormProps {
  initialValues?: AIProvider | null;
  onSuccess: () => void;
  onCancel: () => void;
}

const ProviderForm: React.FC<ProviderFormProps> = ({
  initialValues,
  onSuccess,
  onCancel,
}) => {
  const [form] = Form.useForm();
  const isEdit = !!initialValues?.id;

  // 创建提供商
  const createProvider = 
    async (values: any) => {
      await autoLoginInDev();
      await apiClients.aiChat.aiChatProvidersCreate({
        aIProviderCreateRequest: values,
      });
    } 
  // 更新提供商
  const updateProvider = 
    async (values: any) => {
      await autoLoginInDev();
      await apiClients.aiChat.aiChatProvidersUpdate({
        id: String(initialValues!.id!),
        aIProviderCreateRequest: values,
      });
    } 

  // 表单提交
  const handleSubmit = async (values: any) => {
    // 处理默认参数JSON
    if (values.default_params && typeof values.default_params === 'string') {
      try {
        values.default_params = JSON.parse(values.default_params);
      } catch (error) {
        message.error('默认参数JSON格式错误');
        return;
      }
    }

    if (isEdit) {
      await updateProvider(values);
    } else {
      await createProvider(values);
    }
  };

  // 初始化表单值
  useEffect(() => {
    if (initialValues) {
      const formValues = {
        ...initialValues,
        default_params: initialValues.default_params 
          ? JSON.stringify(initialValues.default_params, null, 2)
          : '{}',
      };
      form.setFieldsValue(formValues);
    }
  }, [initialValues, form]);

  return (
    <ProForm
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      submitter={{
        render: () => (
          <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
            <Button onClick={onCancel}>取消</Button>
            <Button
              type="primary"
              
              onClick={() => form.submit()}
            >
              {isEdit ? '更新' : '创建'}
            </Button>
          </Space>
        ),
      }}
    >
      <ProFormText
        name="name"
        label="提供商名称"
        placeholder="请输入提供商名称"
        rules={[
          { required: true, message: '请输入提供商名称' },
          { max: 100, message: '名称长度不能超过100个字符' },
        ]}
      />

      <ProFormSelect
        name="provider_type"
        label="提供商类型"
        placeholder="请选择提供商类型"
        options={[
          { label: 'OpenAI', value: 'openai' },
          { label: 'Anthropic', value: 'anthropic' },
          { label: 'Google', value: 'google' },
          { label: '自定义', value: 'custom' },
        ]}
        rules={[{ required: true, message: '请选择提供商类型' }]}
      />

      <ProFormText
        name="api_endpoint"
        label="API端点"
        placeholder="请输入API端点URL"
        rules={[
          { required: true, message: '请输入API端点' },
          { type: 'url', message: '请输入有效的URL' },
        ]}
      />

      <ProFormText.Password
        name="api_key"
        label="API密钥"
        placeholder="请输入API密钥"
        rules={[
          { required: true, message: '请输入API密钥' },
          { min: 10, message: 'API密钥长度不能少于10个字符' },
        ]}
      />

      <ProFormTextArea
        name="default_params"
        label="默认参数"
        placeholder="请输入JSON格式的默认参数"
        fieldProps={{
          rows: 6,
        }}
        extra='JSON格式，例如：{"temperature": 0.7, "max_tokens": 2000}'
        rules={[
          {
            validator: (_: any, value: any) => {
              if (!value) return Promise.resolve();
              try {
                JSON.parse(value);
                return Promise.resolve();
              } catch (error) {
                return Promise.reject(new Error('请输入有效的JSON格式'));
              }
            },
          },
        ]}
      />

      <ProFormSwitch
        name="is_active"
        label="是否启用"
        checkedChildren="启用"
        unCheckedChildren="禁用"
        initialValue={true}
      />

      <ProFormSwitch
        name="is_public"
        label="是否公开"
        checkedChildren="公开"
        unCheckedChildren="私有"
        extra="公开的提供商可以被其他用户使用"
        initialValue={false}
      />
    </ProForm>
  );
};

export default ProviderForm;
